import { BaseModel } from './BaseModel'

export interface Setting {
  id: number
  group_name: string
  key_name: string
  key_value: string
  description?: string
  created_at: string
  updated_at: string
}

export interface CreateSettingData {
  group_name: string
  key_name: string
  key_value: string
  description?: string
}

export interface UpdateSettingData {
  group_name?: string
  key_name?: string
  key_value?: string
  description?: string
}

export class SettingsModel extends BaseModel {
  // 获取所有设置
  static async getAll(): Promise<Setting[]> {
    const [rows]: any = await this.query(
      'SELECT * FROM settings ORDER BY group_name ASC, key_name ASC'
    )
    return rows || []
  }

  // 根据分组获取设置
  static async getByGroup(groupName: string): Promise<Setting[]> {
    const [rows]: any = await this.query(
      'SELECT * FROM settings WHERE group_name = ? ORDER BY key_name ASC',
      [groupName]
    )
    return rows || []
  }

  // 根据分组和键名获取设置
  static async getByKey(groupName: string, keyName: string): Promise<Setting | null> {
    const [rows]: any = await this.query(
      'SELECT * FROM settings WHERE group_name = ? AND key_name = ?',
      [groupName, keyName]
    )
    return rows && rows.length > 0 ? rows[0] : null
  }

  // 获取分组设置（以对象形式返回）
  static async getGroupedSettings(groupName: string): Promise<Record<string, any>> {
    const settings = await this.getByGroup(groupName)
    const result: Record<string, any> = {}
    
    for (const setting of settings) {
      try {
        // 尝试解析JSON值，如果不是JSON则直接使用字符串
        result[setting.key_name] = this.parseSettingValue(setting.key_value)
      } catch (error) {
        result[setting.key_name] = setting.key_value
      }
    }
    
    return result
  }

  // 解析设置值
  private static parseSettingValue(value: string): any {
    try {
      return JSON.parse(value)
    } catch (error) {
      return value
    }
  }

  // 创建设置
  static async create(data: CreateSettingData): Promise<number> {
    const result: any = await this.execute(
      'INSERT INTO settings (group_name, key_name, key_value, description) VALUES (?, ?, ?, ?)',
      [data.group_name, data.key_name, data.key_value, data.description || null]
    )
    return result.insertId
  }

  // 更新设置（避免覆盖基类方法，使用updateByKey）
  static async updateByKey(groupName: string, keyName: string, data: UpdateSettingData): Promise<boolean> {
    // 验证 data 参数
    if (!data || typeof data !== 'object' || Array.isArray(data)) {
      throw new Error('data 参数必须是对象')
    }
    
    const fields: string[] = []
    const values: any[] = []

    Object.entries(data).forEach(([key, value]) => {
      if (value !== undefined) {
        fields.push(`${key} = ?`)
        values.push(value)
      }
    })

    if (fields.length === 0) return false

    fields.push('updated_at = CURRENT_TIMESTAMP')
    
    const result: any = await this.execute(
      `UPDATE settings SET ${fields.join(', ')} WHERE group_name = ? AND key_name = ?`,
      [...values, groupName, keyName]
    )

    return result.affectedRows > 0
  }

  // 删除设置（避免覆盖基类方法，使用deleteByKey）
  static async deleteByKey(groupName: string, keyName: string): Promise<boolean> {
    const result: any = await this.execute(
      'DELETE FROM settings WHERE group_name = ? AND key_name = ?',
      [groupName, keyName]
    )
    return result.affectedRows > 0
  }

  // 批量更新设置
  static async batchUpdate(settings: Record<string, any>, groupName: string): Promise<boolean> {
    try {
      // 验证 settings 参数
      if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
        throw new Error('settings 参数必须是对象')
      }
      
      for (const [key, value] of Object.entries(settings)) {
        const existingSetting = await this.getByKey(groupName, key)
        
        if (existingSetting) {
            console.log(existingSetting,key,value);
            
          // 更新现有设置
          await this.updateByKey(groupName, key, {
            key_value: typeof value === 'object' ? JSON.stringify(value) : String(value)
          })
        } else {
          // 创建新设置
          await this.create({
            group_name: groupName,
            key_name: key,
            key_value: typeof value === 'object' ? JSON.stringify(value) : String(value)
          })
        }
      }
      return true
    } catch (error) {
      console.error('批量更新设置失败:', error)
      return false
    }
  }

  // 获取关于我信息（从settings表）
  static async getAboutMe(): Promise<Record<string, any> | null> {
    try {
      return await this.getGroupedSettings('about_me')
    } catch (error) {
      console.error('获取关于我信息失败:', error)
      return null
    }
  }

  // 获取联系信息（从settings表）
  static async getContactInfo(): Promise<Record<string, any> | null> {
    try {
      return await this.getGroupedSettings('contact_info')
    } catch (error) {
      console.error('获取联系信息失败:', error)
      return null
    }
  }

  // 获取英雄区块信息（从settings表）
  static async getHeroSection(): Promise<Record<string, any> | null> {
    try {
      return await this.getGroupedSettings('hero_section')
    } catch (error) {
      console.error('获取英雄区块信息失败:', error)
      return null
    }
  }

  // 获取简历信息（从settings表）
  static async getResume(): Promise<Record<string, any> | null> {
    try {
      return await this.getGroupedSettings('resume')
    } catch (error) {
      console.error('获取简历信息失败:', error)
      return null
    }
  }

  // 获取统计代码信息（从settings表）
  static async getAnalytics(): Promise<Record<string, any> | null> {
    try {
      return await this.getGroupedSettings('analytics')
    } catch (error) {
      console.error('获取统计代码信息失败:', error)
      return null
    }
  }
}